package com.tommy.financial.config.filter;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Package Name: com.tommy.financial.config.filter
 * @Description: TODO
 * @Author Tommy
 * @Date 2019.09.27 23:13
 * @Modify Who      When     What
 * ---------- ----------- -------------
 */
@Component
public class LoginInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        // options请求直接放行
        if (request.getMethod().equals(RequestMethod.OPTIONS.toString())) {
            return true;
        }

        //UserDTO userDTO = (UserDTO) request.getSession().getAttribute(ConstantUtil.LOGINER_SESSION_KEY);
        //// 如果session中没有user，表示没登陆
        //if (userDTO == null){
        //    // 拦截器跨域请求设置
        //    response.setHeader("Access-Control-Allow-Methods", "*");
        //    response.setHeader("Access-Control-Max-Age", "3600");
        //    response.setHeader("Access-Control-Allow-Credentials", "true");
        //    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        //    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        //
        //    // 这个方法返回false表示忽略当前请求，如果一个用户调用了需要登陆才能使用的接口，如果他没有登陆这里会直接忽略掉
        //    // 当然你可以利用response给用户返回一些提示信息，告诉他没登陆
        //    Map<String, Object> result = new HashMap<>();
        //    result.put("code", ResultEnum.LOGIN_CANCEL.getCode());
        //    result.put("message", ResultEnum.LOGIN_CANCEL.getContent());
        //    // 防止中文乱码
        //    response.setContentType("text/html;charset=UTF-8");
        //    response.getWriter().write(JSONObject.toJSON(result).toString());
        //    return false;
        //}else {
        //    return true;    // 如果session里有user，表示该用户已经登陆，放行，用户即可继续调用自己需要的接口
        //}
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}

